#include <stdio.h>
#include <stdlib.h>

#include "simpleTime.h"


unsigned long get_time(){
	struct timeval tv;
	gettimeofday(&tv, NULL);
	
	//Part of the sec is needed to keep value increasing, 
	//as microseconds would count from zero each second.
	unsigned long cur_time=tv.tv_sec;
	//printf("sec: %ld, &:%ld, microsec: %ld", cur_time, cur_time & 0xff, tv.tv_usec);
	cur_time = 1000000*(cur_time & 0xff) + tv.tv_usec;
	//printf(" cur_time: %ld\n", cur_time);
	return cur_time;  //microseconds
}


void delay(int milliseconds){
	unsigned long last_t = get_time();
	while (last_t + milliseconds*1000 > get_time()) {/*delay*/}
}


void rate(int freq) {
	static unsigned long last_t;
	unsigned long interval = 1000000 / freq;  //microseconds
	
	//printf("interval: %d, last_t: %ld \n",interval, last_t);
	while ((last_t + interval) > get_time()) {
		for (int i=0; i<10; i++) {/*delay*/}
	}
	last_t = get_time();
	
}
